﻿using DTM.Core.Exceptions;
using DTM.Core.Utils;
using DTM.Domain.Players;
using DTM.Repository;
using System;
using System.Windows.Forms;

namespace DTM.WinApp.Players
{
    /// <summary>
    /// Presenter of player edit view.
    /// </summary>
    internal class PlayerPresenter : Presenter<IPlayerView>, IPlayerPresenter
    {
        #region Fields

        private readonly IApplicationManager _manager;
        private readonly IPlayerService _service;

        #endregion Fields

        #region Constructors

        public PlayerPresenter(IApplicationManager manager, IPlayerService service)
        {
            Validate.NotNull<ArgumentNullException>(service, "service");
            _service = service;
            Validate.NotNull<ArgumentNullException>(manager, "manager");
            _manager = manager;
        }

        #endregion Constructors

        #region Methods

        protected override void InitalizeView()
        {
            View.DeletePlayer += View_DeletePlayer;
            View.SavePlayer += View_SavePlayer;
            View.UpdatePlayer += View_UpdatePlayer;
        }

        private void View_DeletePlayer(object sender, EventArgs e)
        {
            _service.Delete(View.PlayerId);
            View.Close(DialogResult.OK);
        }

        private void View_SavePlayer(object sender, EventArgs e)
        {
            var player = new Player()
            {
                Name = View.PlayerName,
                Surname = View.PlayerSurname,
                Email = View.PlayerEmail
            };
            try
            {
                _service.Insert(player);
                View.Close(DialogResult.OK);
            }
            catch (CustomValidationException ex)
            {
                _manager.ShowErrorMessage(ex.Message);
            }
        }

        private void View_UpdatePlayer(object sender, EventArgs e)
        {
            var player = new Player()
            {
                Id = View.PlayerId,
                Name = View.PlayerName,
                Surname = View.PlayerSurname,
                Email = View.PlayerEmail
            };
            try
            {
                _service.Update(player);
                View.Close(DialogResult.OK);
            }
            catch (CustomValidationException ex)
            {
                _manager.ShowErrorMessage(ex.Message);
            }
        }

        #endregion Methods
    }
}